<template>
  <el-input v-model="state.input"  placeholder="题库名称" @blur="handleInput" @keyup.enter="handleInput"
    :prefix-icon="Search" size="large" class="margin10px"></el-input>
  <br>
  <el-button type="primary" class="margin10px" @click="addClick" size="large" style="width: 90px;">+&nbsp;添加</el-button>
  <br>
  <el-select class="margin10px" v-model="selectValue" clearable :placeholder="selectPlaceholder" 
    size="large" v-if="state.selectedRows.length > 0" @change="handleSelectChange">
    <el-option label="删除" value="delete" />
  </el-select>
  <el-table :data="state.bankHaveQuestionSums" border style="width: 100%" header-background="#f2f3f4"
    @selection-change="handleSelectionChange" tooltip-effect="dark">
    <el-table-column type="selection" width="55" />
    <el-table-column property="questionBank.bankName" label="题库名称" />
    <el-table-column property="singleChoice" label="单选题数量" />
    <el-table-column property="multipleChoice" label="多选题数量" />
    <el-table-column property="judge" label="判断题数量" />
    <el-table-column property="shortAnswer" label="简答题数量" />
  </el-table>
  <br>
  <!-- 分页查询 -->
  <div class="demo-pagination-block">
    <div class="demonstration"></div>
    <el-pagination v-model:current-page="state.pageNum" v-model:page-size="state.pageSize" :page-sizes="[5, 10, 15, 20]"
      :page-size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="state.total" @size-change="handleSizeChange" @current-change="handleCurrentChange">
    </el-pagination>
  </div>

  <!-- 删除提示框 -->
  <el-dialog v-model="dialogDelete" title="提示" width="700" :before-close="deleteCancel" align-center>
    <span>此操作将永久删除该题库, 是否继续?</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteCancel">取消</el-button>
        <el-button type="primary" @click="deleteQuestionBank">
          删除
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加提示框 -->
  <el-dialog v-model="dialogAdd" title="添加题库" width="500" :before-close="addCancel">
    <template #footer>
      <div class="dialog-footer">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="formData" :rules="rules" label-width="auto"
          class="demo-ruleForm" :size="formSize" status-icon>
          <el-form-item label="题库名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
        </el-form>
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addQuestionBank">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElNotification, FormRules } from 'element-plus'
import {
  getBankHaveQuestionSumByType,
  deleteQuestionBankById,
  getExamRecord,
} from '@/api/examControl/QuestionBankMange'
interface RuleForm {
  name: string
}

// 删除提示框是否显示
const dialogDelete = ref(false)
// 添加提示框是否显示
const dialogAdd = ref(false)

// 添加的题库名
const formData = reactive<RuleForm>({
  name: '',
});
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入题库名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度3-15个字符', trigger: 'blur' },
  ],
})
// 定义数据
const state = reactive({
  bankHaveQuestionSums: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  input: '',
  selectedRows: [],
});

const value = ref(''); // el-select的值

// 分页查询属性
const size = ref('default');
const background = ref(false);
const disabled = ref(false);

// 动态更新 select
const selectPlaceholder = ref('');
const selectValue = ref('');

// 分页大小变化和当前页变化的事件处理函数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  state.pageSize = val;
  getBankControl();
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  state.pageNum = val;
  getBankControl();
};

// 获取题库列表
async function getBankControl() {
  try {
    let {data} = await getBankHaveQuestionSumByType( {
        bankName: state.input,
        pageNo: state.pageNum,
        pageSize: state.pageSize,
      },
    );
    console.log("输出一下");
    console.log(data.data);
    state.bankHaveQuestionSums = data.data.bankHaveQuestionSums;
    state.total = data.data.total;
    console.log("输出一下");
    
    console.log(state.total);
    
  } catch (error) {
    console.error('获取题库列表时出错:', error);
  }
}

// 输入框失去焦点或按下回车键时的事件处理函数
const handleInput = () => {
  getBankControl();
};

// 处理选中行变化的函数
const handleSelectionChange = (selectedRows: any[]) => {
  state.selectedRows = selectedRows;
  console.dir(state.selectedRows)
  selectValue.value = '';
  selectPlaceholder.value = `已选择${selectedRows.length}项`;
};

// 删除选中行
async function deleteQuestionBank() {
  const ids = state.selectedRows.map(row => row.questionBank.bankId).join(',');
  console.log(`删除的题库 IDs: ${ids}`); // 输出 ids 字符串
  try {
    const {data} = await deleteQuestionBankById({ ids });
    console.log(data); // 输出服务器返回的响应
    state.selectedRows = []; // 清空选中行
    dialogDelete.value = false
    ElMessage({
      message: '删除成功!',
      type: 'success',
    })
    getBankControl(); // 刷新列表
  } catch (error) {
    ElMessage.error('删除失败!')
    console.error('删除请求出错:', error);

  } finally {
    selectPlaceholder.value = '';
  }
}

// 取消删除
function deleteCancel() {
  dialogDelete.value = false
  ElMessage({
    message: '已取消删除!',
    type: 'warning',
  })
}

// 处理 el-select 变化的函数
const handleSelectChange = (value: string) => {
  if (value === 'delete') {
    dialogDelete.value = true
  }
};

// 点击添加显示添加框
function addClick() {
  dialogAdd.value = true
}

// 添加题库
async function addQuestionBank() {
  try {
    const response = await getExamRecord({
      bankName: formData.name
    });
    console.log(response); // 输出服务器返回的响应
    dialogAdd.value = false;
    ElNotification({
      title: 'Success',
      message: '添加题库成功!',
      type: 'success',
    })
    getBankControl(); // 刷新列表
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: '添加题库失败',
      type: 'error',
    })
    console.error('添加请求出错:', error);
  }
}

// 取消添加
function addCancel() {
  dialogAdd.value = false
}

// 组件挂载时获取题库列表
onMounted(() => {
  getBankControl();
});
</script>

<style >
.margin10px
{
  margin-bottom: 10px;
  width: 220px
}

.demo-pagination-block+.demo-pagination-block
{
  margin-top: 10px;
}

.demo-pagination-block .demonstration
{
  margin-bottom: 16px;
}

.el-table th.el-table__cell
{
  background-color: #f2f3f4;
}

.big .el-table
{
  box-shadow: 0 0 1px 1px #dcdcdc;
}

.el-table thead
{
  color: #555;
  font-weight: 800;
  height: 50px;
}

.el-table .cell
{
  text-align: center;
  min-height: 40px;
}

.el-table td.el-table__cell
{
  border-bottom: none;
}
</style>
